package com.liuwei.spring.cloud.junit.redisson;

import com.liuwei.spring.cloud.common.utils.Radix;
import com.liuwei.spring.cloud.framework.spring.ApplicationHelper;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RedissonClient;

public class RedissonJunit {

    public static void main(String[] args) {
        RedissonClient redisson = ApplicationHelper.getBean(RedissonClient.class);
        String key = "";
        RAtomicLong item = redisson.getAtomicLong(key);
        long updated = item.incrementAndGet();
        String unique = Radix.toRadixString(updated,32);
    }

    /**
     * 通过 Redis 生成自增的 ID
     * @param prefix   前缀
     * @param date  日期编码
     * @param redisKey 键名
     * @return prefix+date+code(redisKey)
     */
    public String generateCode(String prefix,String date,String redisKey){
        RedissonClient redisson = ApplicationHelper.getBean(RedissonClient.class);
        RAtomicLong item = redisson.getAtomicLong(redisKey);
        long updated = item.incrementAndGet();
        String unique = Radix.toRadixString(updated,32);
        return StringUtils.defaultIfEmpty(prefix,"") + StringUtils.defaultIfEmpty(date,"") + StringUtils.leftPad(unique,8,"0");
    }
}
